package com;

import com.baomidou.mybatisplus.annotation.TableId;
import lombok.Data;

import java.lang.reflect.Field;
import java.sql.Connection;
import java.sql.DriverManager;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.Optional;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Data
public class ObjToTable {

    private String driver;
    private String dataSourceUrl;
    private String user;
    private String password;
    private Class[] objLists;

    private static Pattern columnRegex = Pattern.compile( "[A-Z]");

    public void setObjLists(Class... objLists) {
        this.objLists = objLists;
    }

    private Connection getConnection() throws Exception{

        Class.forName(this.driver);
        Connection connection = DriverManager.getConnection(this.dataSourceUrl, this.user, this.password);


        return connection;

    }


    public void autoCreateTableByObj() throws Exception{
        Connection connection = getConnection();

        StringBuilder stringBuilder = new StringBuilder();
        for(Class clazz : this.objLists){

        }
    }


    private String getCreateTableSqlString(Class aClass){

        Field[] declaredFields = aClass.getDeclaredFields();

        StringBuilder sb = new StringBuilder();

        sb.append("create table ");
        sb.append(humpToLine(aClass.getSimpleName()).substring(1));
        sb.append("(\n");

        for (Field field : declaredFields){
            field.setAccessible(true);

            sb.append(humpToLine(field.getName()));
            sb.append("\t");
            sb.append(getDbTypeByJavaType(field.getType()));

            TableId annotation = field.getAnnotation(TableId.class);

            if(annotation != null){

            }
        }
        return null;

    }





    private String humpToLine(String hump){
        Matcher matcher = columnRegex.matcher(hump);

        StringBuffer sb = new StringBuffer();

        while(matcher.find()){
            matcher.appendReplacement(sb,"_" + matcher.group(0).toLowerCase());
        }

        matcher.appendTail(sb);

        return sb.toString();
    }

    private String getDbTypeByJavaType(Class type){
        String result = null;

        if(type == String.class){
            result = "varchar(50)";
        }else if(type == int.class || type == Integer.class){
            result = "int";
        }else if(type == double.class || type == Double.class){
            result = "double";
        }else if(type == float.class || type == Float.class){
            result = "float";
        }else if(type == boolean.class || type == Boolean.class){
            result = "tinyint(1)";
        }else if(type == Date.class || type == LocalDateTime.class || type == LocalDate.class){
            result = "timestamp";
        }

        return result;
    }

}
